﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using GMAC.ReportingSystem.Business.Entities;
using System.Data;
using FrameworkManapro.Utilities;
using GMAC.ReportingSystem.Business.Components;

namespace GMAC.ReportingSystem.Paginas
{
    public partial class AccountsWithDebitBalances : System.Web.UI.Page
    {
        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated || Session["User"] == null)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }

            if (IsPostBack)
            {
                return;
            }

            Initialize();
            ValidateSecurity();
        }

        #endregion

        ///////////////////////////////////////////////////////////////////

        #region Button Events

        
        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible  = true;
            
            var bc = new AccountDebitBalanceComponent();
            
            try
            {
                var account = ReadAccountDebitBalance();

                var oldAccount = bc.GetDetails(account.AccountNumber);
                
                bc.Edit(account);

                var audit = new FrameworkManapro.Audit.Audit<AccountDebitBalance>
                {
                    EntityKey = account.AccountNumber,
                    EventDate = DateTime.Now,
                    EventType = FrameworkManapro.Audit.AuditEvent.Update,
                    OldObject = account,
                    NewObject = account,
                    UserId    = ((User)Session["User"]).UserID
                };

                var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<AccountDebitBalance>(audit);
                auditDAC.InsertAudit();
                wucMessage.ShowMessage(UserControls.MessageType.Success, "The Account was successfully saved.", null);
                popupExtenderMessage.Show();
                Search();
                ClearFields();

            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Save Account", "btnSave_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Account couldn't be saved.", null);
                popupExtenderMessage.Show();
            }
        }
        
        //-----------------------------------------------------------------
        
        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            ClearFields();
        }

        //-----------------------------------------------------------------
        
        protected void btnModify_Click(object sender, ImageClickEventArgs e)
        {
            if (grvAccountsWithDebitBalances != null)
            {
                if (grvAccountsWithDebitBalances.SelectedDataKey != null)
                {
                    try
                    {
                        var accountNumber = (string)grvAccountsWithDebitBalances.SelectedDataKey.Value;
                        var bc            = new AccountDebitBalanceComponent();
                        var account       = bc.GetDetails(accountNumber);

                        txtSubscriber.Text                = (!string.IsNullOrEmpty(account.AccountNumber)) ? account.AccountNumber : string.Empty;
                        ddlProductType.SelectedValue      = (!account.AccountTypeID.Equals(null)) ? account.AccountTypeID.AccountTypeID.ToString() : string.Empty;
                        ddlBank.SelectedValue             = (!string.IsNullOrEmpty(account.DebitBankNumber)) ? account.DebitBankNumber : string.Empty;
                        ddlPaymentType.SelectedValue      = (!account.PaymentType.Equals(null)) ? ((int)account.PaymentType).ToString() : string.Empty;
                        txtEmissionDays.Text              = (!account.EmissionDays.Equals(null)) ? account.EmissionDays.ToString() : string.Empty;
                        ddlStatusLAORetail.SelectedValue  = (!account.StatusLAORetail.Equals(null)) ? ((int)account.StatusLAORetail).ToString() : string.Empty;
                        ddlStatus.SelectedValue           = (!account.StatusSalvageTransferReason.Equals(null)) ? ((int)account.StatusSalvageTransferReason).ToString() : string.Empty;
                        ddlEmissionTime.SelectedValue     = (!account.IssueTime.Equals(null)) ? ((int)account.IssueTime).ToString() : string.Empty;
                        txtPendingAmount.Text             = (!account.PendingAmount.Equals(null)) ? ((decimal)account.PendingAmount).ToString() : string.Empty;
                        txtDateProyection.Text            = (!account.ProjectionDate.Equals(null)) ? account.ProjectionDate.ToShortDateString() : string.Empty;
                        txtEmissionDate.Text              = (!account.IssueDate.Equals(null)) ? account.IssueDate.ToShortDateString() : string.Empty;
                        ddlType.SelectedValue             = (!account.AccountType.Equals(null)) ? ((int)account.AccountType).ToString() : null;

                        ddlType.SelectedValue             = (!account.AccountType.Equals(null)) ? ((int)account.AccountType).ToString() : string.Empty;
                        ddlInsuranceCompany.SelectedValue = (!account.InsuranceCompany.Equals(null)) ? ((int)account.InsuranceCompany.Id).ToString() : string.Empty;

                        btnSave.Visible = true;
                        btnNew.Visible  = false;
                    }
                    catch (Exception ex)
                    {
                        FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Modify user", "btnModify_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                        wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred changing the user.", ex.ToString());
                        popupExtenderMessage.Show();
                    }
                }
                else
                {
                    wucMessage.ShowMessage(UserControls.MessageType.Information, "A user must be selected.", null);
                    popupExtenderMessage.Show();
                }
            }
        }    
        
        //-----------------------------------------------------------------
        
        protected void btnConfirm_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var bc = new AccountDebitBalanceComponent();

                if (grvAccountsWithDebitBalances.SelectedDataKey != null)
                {
                    var accountNumber = (string)this.grvAccountsWithDebitBalances.SelectedDataKey.Value;

                    var account = new AccountDebitBalance { AccountNumber = accountNumber };

                    var oldAccount = bc.GetDetails(account.AccountNumber);

                    bc.Delete(account);
                    
                    var audit = new FrameworkManapro.Audit.Audit<AccountDebitBalance>
                    {
                        EntityKey = account.AccountNumber,
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Delete,
                        OldObject = oldAccount,
                        UserId    = ((User)Session["User"]).UserID
                    };

                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<AccountDebitBalance>(audit);
                    
                    auditDAC.InsertAudit();
                    
                    this.PagingControl.TotalRecords = Search();
                    
                    Search();
                    
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The Account was successfully deleted.", null);
                    
                    popupExtenderMessage.Show();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Delete Account With Debit Balances", "btnConfirm_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Account couldn't be deleted.", ex.ToString());
                popupExtenderMessage.Show();
            }
        }

        //-----------------------------------------------------------------
        
        protected void imgBuscarReg_Click(object sender, ImageClickEventArgs e)
        {
            this.PagingControl.TotalRecords = Search();
            Search();
            if (this.PagingControl.TotalRecords == 0)
            {
                PagingControl.Visible = false;
            }
            else
            {
                PagingControl.Visible = true;
            }
            ClearFields();
            
        }

        //-----------------------------------------------------------------
        
        protected void imgRefresh_Click(object sender, ImageClickEventArgs e)
        {
            
        }

        //-----------------------------------------------------------------
        
        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            if (grvAccountsWithDebitBalances.SelectedValue != null)
            {
                popupExtenderConfirm.Show();
            }
            else
            {
                wucMessage.ShowMessage(UserControls.MessageType.Information, "A Account must be selected.", null);
                popupExtenderMessage.Show();
            }
        }

        //-----------------------------------------------------------------
        
        protected void btnNew_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var bc = new AccountDebitBalanceComponent();

                var account = ReadAccountDebitBalance();

                bc.Create(account);
                
                var audit = new FrameworkManapro.Audit.Audit<AccountDebitBalance>
                {
                    EntityKey = account.AccountNumber,
                    EventDate = DateTime.Now,
                    EventType = FrameworkManapro.Audit.AuditEvent.Insert,
                    NewObject = account,
                    UserId    = ((User)Session["User"]).UserID
                };
                
                var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<AccountDebitBalance>(audit);
                
                auditDAC.InsertAudit();
                
                wucMessage.ShowMessage(UserControls.MessageType.Success, "The user was successfully saved.", null);
                
                popupExtenderMessage.Show();
                
                this.PagingControl.TotalRecords = Search();
                
                Search();
                
                ClearFields();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "New user", "btnNew_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The user could not be saved", null);
                popupExtenderMessage.Show();
            }
        }
        
        #endregion

        ///////////////////////////////////////////////////////////////////

        #region Other Events

        protected void grvAccountsWithDebitBalances_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["OnClick"] = ClientScript.GetPostBackEventReference(grvAccountsWithDebitBalances, "Select$" + e.Row.RowIndex);
            }
        }

        #endregion

        ///////////////////////////////////////////////////////////////////

        #region Private Methods

        private void ClearFields()
        {
            //Textboxes

            txtDateProyection.Empty();
            txtEmissionDate.Empty();
            txtEmissionDateSearch.Empty();
            txtEmissionDays.Empty();
            txtPendingAmount.Empty();
            txtSubscriber.Empty();
            txtSubscriberSearch.Empty();

            //DropDownLists

            ddlBank.SelectFirstItem();
            ddlEmissionTime.SelectFirstItem();
            ddlEmissionTimeSearch.SelectFirstItem();
            ddlInsuranceCompany.SelectFirstItem();
            ddlInsuranceCompanySearch.SelectFirstItem();
            ddlPaymentType.SelectFirstItem();
            ddlProductType.SelectFirstItem();
            ddlStatus.SelectFirstItem();
            ddlStatusLAORetail.SelectFirstItem();
            ddlType.SelectFirstItem();
            ddlTypeSearch.SelectFirstItem();
        }

        //-----------------------------------------------------------------
        
        private void Initialize()
        {
            try
            {
                // Type Search

                ddlTypeSearch.BindEnumValue<GeneralEnumTypes.TypeAccountsWithDebitBalances>("Select...");
                
                //Type Detail

                ddlType.BindEnumValue<GeneralEnumTypes.TypeAccountsWithDebitBalances>("Select...");

                // Emission Time Search

                ddlEmissionTimeSearch.BindEnumValueReflection<GeneralEnumTypes.EmissionTime>("Select...");

                // Emission Time Detail

                ddlEmissionTime.BindEnumValueReflection<GeneralEnumTypes.EmissionTime>(" ");

                //Payment Type

                ddlPaymentType.BindEnumValue<GeneralEnumTypes.PaymentType>(" ");

                //Status LAO Retail

                ddlStatusLAORetail.BindEnumValueReflection<GeneralEnumTypes.StatusLAORetail>(" ");

                //Status

                ddlStatus.BindEnumValue<GeneralEnumTypes.InternalStatus>(" ");

                //-----------------------------------
                // Banks
                //-----------------------------------

                var            bcBank  = new Business.Components.BankComponent();
                BankCollection banks   = bcBank.GetList();

                ddlBank.DataSource     = banks;
                ddlBank.DataTextField  = "DebitBankName";
                ddlBank.DataValueField = "DebitBankNumber";

                ddlBank.DataBind();

                ddlBank.Items.Insert(0, new ListItem("", String.Empty));

                //-----------------------------------
                // Products (Account Types)
                //-----------------------------------

                var               bcProduct   = new Business.Components.ProductComponent();
                ProductCollection products    = bcProduct.GetList();

                ddlProductType.DataSource     = products;
                ddlProductType.DataTextField  = "Description";
                ddlProductType.DataValueField = "AccountTypeId";

                ddlProductType.DataBind();

                ddlProductType.Items.Insert(0, new ListItem("", String.Empty));

                //-----------------------------------
                // Insurance Companies
                //-----------------------------------

                var                        bcCompanies   = new Business.Components.InsuranceCompanyComponent();
                InsuranceCompanyCollection companies     = bcCompanies.GetList();

                ddlInsuranceCompany.DataSource           = companies;
                ddlInsuranceCompany.DataTextField        = "Name";
                ddlInsuranceCompany.DataValueField       = "Id";
                ddlInsuranceCompany.DataBind();

                ddlInsuranceCompanySearch.DataSource     = companies;
                ddlInsuranceCompanySearch.DataTextField  = "Name";
                ddlInsuranceCompanySearch.DataValueField = "Id";

                ddlInsuranceCompanySearch.DataBind();

                ddlInsuranceCompanySearch.Items.Insert(0, new ListItem("Select...", String.Empty));
                ddlInsuranceCompany.Items.Insert(0, new ListItem("Select...", String.Empty));

                //-----------------------------------

                btnSave.Visible = false;
                wucMessageConfirm.ShowMessage(UserControls.MessageType.Information, "Are you sure you want to delete the selected Account", null);
                
                this.PagingControl.TotalRecords = Search();
                
                Search();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Initialize page", "Initialize", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error occurred initializing the page.", ex.ToString());
                popupExtenderMessage.Show();
            }

        }

        //-----------------------------------------------------------------
        
        private void ValidateSecurity()
        {
            var beEntities = ((User)Session["User"]).Role.Security.GetEntitySecurity("AccountsWithDebitBalances");
            
            if (beEntities == null) return;
            
            if (!beEntities.CanRead)
            {
                this.grvAccountsWithDebitBalances.Visible = false;
                
                btnModify.Visible = false;
                btnDelete.Visible = false;
                pnlSearch.Visible = false;
            }
            if (!beEntities.CanWrite)
            {
                btnSave.Visible = false;
            }
            if (!beEntities.CanInsert)
            {
                btnNew.Visible = false;
                btnCancel.Visible = false;
                pnlEdit.Visible = false;
            }
            if (!beEntities.CanDelete)
            {
                btnDelete.Visible = false;
            }
        }

        //-----------------------------------------------------------------
        
        private int Search()
        {
            try
            {
                var bc = new AccountDebitBalanceComponent();

                //-------------------

                string accountNumber = txtSubscriberSearch.Text;

                GeneralEnumTypes.TypeAccountsWithDebitBalances? accountType = (!ddlType.SelectedValue.Equals(string.Empty)) 
                    ? (GeneralEnumTypes.TypeAccountsWithDebitBalances?)int.Parse(ddlType.SelectedValue) : null;

                int? insuranceCompany = (!string.IsNullOrEmpty(ddlInsuranceCompanySearch.SelectedValue)) ? (int?)int.Parse(ddlInsuranceCompanySearch.SelectedValue) : null;

                DateTime? issueDate   = (!string.IsNullOrEmpty(txtEmissionDateSearch.Text)) ? (DateTime?)DateTime.Parse(txtEmissionDateSearch.Text) : null;

                int? emissionDays     = (!string.IsNullOrEmpty(txtEmissionDaysSearch.Text)) ? (int?)int.Parse(txtEmissionDaysSearch.Text.ToString()) : null;

                GeneralEnumTypes.EmissionTime? emissionTime = (!ddlEmissionTimeSearch.SelectedValue.Equals(string.Empty))
                    ? (GeneralEnumTypes.EmissionTime?)int.Parse(ddlEmissionTimeSearch.SelectedValue) : null;

                //-------------------

                FrameworkManapro.WebUI.PagingDetails paging = new FrameworkManapro.WebUI.PagingDetails();
                
                paging.PageNumber    = this.PagingControl.PageNumber;
                paging.PageSize      = this.PagingControl.PageSize;
                paging.SortBy        = this.PagingControl.SortExpression;
                paging.SortDirection = this.PagingControl.SortDirection;

                AccountDebitBalanceCollection accountDebitBalances = bc.Search(accountNumber, accountType, insuranceCompany, issueDate, emissionDays, emissionTime, paging);

                grvAccountsWithDebitBalances.DataSource = accountDebitBalances;
                grvAccountsWithDebitBalances.DataBind();

                return accountDebitBalances.TotalResults;
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Search user", "void Search", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred during the search.", ex.ToString());
                popupExtenderMessage.Show();

                grvAccountsWithDebitBalances.DataSource = GenerateDataTablePrueba();
                grvAccountsWithDebitBalances.DataBind();
                
                return 1;
            }
        }

        //-----------------------------------------------------------------

        private AccountDebitBalance ReadAccountDebitBalance()
        {
            AccountDebitBalance account = new AccountDebitBalance();

            account.AccountNumber    = txtSubscriber.Text;
            account.AccountType      = (GeneralEnumTypes.TypeAccountsWithDebitBalances)int.Parse(ddlType.SelectedValue);
            account.AccountTypeID    = new Product { AccountTypeID = int.Parse(this.ddlProductType.SelectedValue) };
            account.DebitBankNumber  = ddlBank.SelectedValue;

            account.EmissionDays     = int.Parse(this.txtEmissionDays.Text);
            
            account.InsuranceCompany = new InsuranceCompany { Id = int.Parse(ddlInsuranceCompany.SelectedValue) };
            account.IssueDate        = DateTime.Parse(txtEmissionDate.Text);
            account.IssueTime        = (GeneralEnumTypes.EmissionTime)int.Parse(ddlEmissionTime.SelectedValue);
            account.PaymentType      = (GeneralEnumTypes.PaymentType)int.Parse(ddlPaymentType.SelectedValue);
            account.PendingAmount    = decimal.Parse(txtPendingAmount.Text);
            account.ProjectionDate   = DateTime.Parse(txtDateProyection.Text);
            account.StatusLAORetail  = (GeneralEnumTypes.StatusLAORetail)int.Parse(ddlStatusLAORetail.SelectedValue);

            account.StatusSalvageTransferReason = (GeneralEnumTypes.InternalStatus)int.Parse(ddlStatusLAORetail.SelectedValue);
            
 
            return account;
        }

        //-----------------------------------------------------------------

        protected void pagingControl_PageChanged(object sender, EventArgs e)
        {
            Search();
        }
        
        #endregion

        ///////////////////////////////////////////////////////////////////

        #region Tests

        private DataTable GenerateDataTablePrueba()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Accountnumber", typeof(string));
            dt.Columns.Add("Type", typeof(string));
            dt.Columns.Add("InsuranceCompany", typeof(string));
            dt.Columns.Add("ID", typeof(string));
            DataRow rowdt;
            rowdt = dt.NewRow();
            rowdt[0] = "0002287262622552";
            rowdt[1] = "Robo";
            rowdt[2] = "Seguros Caracas";
            rowdt[3] = "1";
            
            dt.Rows.Add(rowdt);


            
           

            return dt;

        }

        #endregion

    }
    
    ///////////////////////////////////////////////////////////////////
    
    #region Control Extension Methods

    public static class Extensiones
    {
        #region Static Methods

        //----------------------------------------
        /// <summary>
        /// Ricardo Recaredo (08/14/2011)
        /// </summary>
        /// <param name="ddl">Texbox to Clear</param>
        //----------------------------------------

        public static void Empty(this TextBox tb)
        {
            tb.Text = string.Empty;
        }

        //----------------------------------------
        /// <summary>
        /// Ricardo Recaredo (08/14/2011)
        /// </summary>
        /// <param name="ddl">Dropdownlist to Clear</param>
        //----------------------------------------

        public static void Empty(this DropDownList ddl)
        {
            ddl.Items.Clear();
        }

        //----------------------------------------
        /// <summary>
        /// Ricardo Recaredo (08/14/2011)
        /// </summary>
        /// <param name="ddl">Dropdownlist to Clear</param>
        //----------------------------------------

        public static void SelectFirstItem(this DropDownList ddl)
        {
            ddl.SelectedIndex = 0;
        }

        //----------------------------------------
        /// <summary>
        /// Ricardo Recaredo (08/14/2011)
        /// </summary>
        /// <param name="ddl">Dropdownlist to Populate</param>
        //----------------------------------------

        public static void BindEnumValue<T>(this ListControl ddl, string initialValue)
        {
            if (!typeof(T).IsEnum)
            {
                throw new InvalidConstraintException("Generic T must be a Enum type");
            }

            foreach (int i in Enum.GetValues(typeof(T)))
            {
                ddl.Items.Add(new ListItem(Enum.GetName(typeof(T), i).ToString(), i.ToString()));

                ddl.DataBind();
            }

            if (!string.IsNullOrEmpty(initialValue))
            {
                ddl.Items.Insert(0, new ListItem(initialValue, String.Empty));
            }
        }

        //----------------------------------------
        /// <summary>
        /// Ricardo Recaredo (08/14/2011)
        /// </summary>
        /// <param name="ddl">Dropdownlist to Populate</param>
        //----------------------------------------

        public static void BindEnumValueReflection<T>(this ListControl ddl, string initialValue)
        {
            if (!typeof(T).IsEnum)
            {
                throw new InvalidConstraintException("Generic T must be a Enum type");
            }

            foreach (Enum i in Enum.GetValues(typeof(T)))
            {
                ddl.Items.Add(new ListItem(i.ToDescription(), (Convert.ToInt32(i)).ToString()));

                ddl.DataBind();
            }

            if (!string.IsNullOrEmpty(initialValue))
            {
                ddl.Items.Insert(0, new ListItem(initialValue, String.Empty));
            }
        }

        #endregion
    }

    #endregion
}
